<?php
namespace app\api\controller;
use app\model\User as UserModel;
use app\model\Integral as IntegralModel;
use app\model\Token as TokenModel;
use think\Db;


class User extends Base
{
    protected $noCheckToken = ['login','ranking','callback','alogin'];


    /**
     * 获取详情
     * @Author   cch
     * @DateTime 2020-05-26T17:22:45+0800
     * @return   [type]                   [description]
     */
    public function read(){
        $user_id = $this->login_user['user_id'];
        if (empty($user_id)) {
            exception('请登录后操作',400);
        }

        $model = new UserModel();
        $data = $model->where('id',$user_id)->find();
        if (!empty($data)) {
            $data['is_sign'] = Db::name('sign')->where([
                ['user_id','=',$data['id']],
                ['ctime','=',date('Y-m-d')]
            ])->count();

            $data['is_vip'] = $data['vip_time'] >= date('Y-m-d') ? 1 : 0;
        }
        return apiResult('2000','获取成功',$data);
    }

    /**
     * @Author   CCH
     * @DateTime 2020-05-23T12:10:10+0800
     * @return   数据列表
     */
    public function invites(){
        $ulogin = $this->login_user;
        $map_params = [
            
        ];
        $map = getSearchParam($map_params);
        $map[] = ['invite_id','=',$ulogin['user_id']];

        $model = new UserModel();
        $page_param = ['page'=>input('page_index',1),'list_rows'=>input('page_size',10)];
        $list = $model->where($map)->order('id desc')->paginate($page_param)->toarray();
        foreach ($list['data'] as $k => $vo) {
            
        }
        return apiResult('2000','获取成功',$list);
    }

    /**
     * 获取详情
     * @Author   cch
     * @DateTime 2020-05-26T17:22:45+0800
     * @return   [type]                   [description]
     */
    public function login($code){
        $config = config('config.wxparam');
        $url = 'https://api.weixin.qq.com/sns/jscode2session?appid='.$config['appid'].'&secret='.$config['secret'].'&js_code='.$code.'&grant_type=authorization_code';

        $user_code = file_get_contents($url); //获取session_key 跟openid 
        // $user_code = '{"session_key":"epSkgVvQeNLDLhkWZRq4KQ==","openid":"oTn0T5aHGhEKLhbMeb1gG3A6WhzN"}';
        $user_code = json_decode($user_code,true);

        if (!empty($user_code['openid'])) {
            $model = new UserModel();
            $save_data = [
                'openid'=>$user_code['openid'],
                'login_time'=>time()
            ];

            // 如果用户已存在，更新token返回
            $uinfo = $model->where('openid',$save_data['openid'])->find();
            $user_id = $uinfo['id'];
            if (!empty($user_id)) {
                $access_token = TokenModel::where('user_id',$user_id)->value('access_token');
                $token_data = [
                    'user_id'=>$user_id,
                    'access_token'=>empty($access_token)?uuidCreate():$access_token,
                    'expiry_time'=>date('Y-m-d H:i:s',strtotime('+7 days')),
                    'session_key'=>$user_code['session_key'],
                    'is_first'=>0,
                    'openid'=>$uinfo['openid']
                ];
                TokenModel::where('user_id',$user_id)->delete();
                if ( TokenModel::insert($token_data) ) {
                    // 更新登录时间
                    $model->where('openid',$save_data['openid'])->update([
                        'login_time'=>time()
                    ]);
                    return apiResult('2000','登录成功',$token_data);
                }else{
                    return apiResult('5000','登录异常');
                }
            }
       
            Db::startTrans();
            try{
                if ( $model->where('openid',$save_data['openid'])->count() > 0 ) {
                    throw new \Exception("该OPENID已存在");
                }
                if ( empty($user_id)) {
                    if (input('invite_id',0) > 0) {
                        $invite_id = input('invite_id');
                        $save_data['invite_id'] = $invite_id;
                        IntegralModel::saveData([
                            'user_id'=>$invite_id,
                            'remark'=>'邀请用户获得积分',
                            'amount'=>Db::name('config')->where('key','INVITE_INTEGRAL')->value('value')
                        ]);
                    }
                    $save_data['source'] = 1; 
                    $save_data['status'] = 1; 
                    $save_data['ctime'] = time();
                    $save_data['nickname'] = '用户'.date('His');
                    // $save_data['headimgurl'] = '20231123/96CA190873CA42E8A1B56E74B0326030.png';
                    $save_data['headimgurl'] = Db::name('config')->where('key','USER_DEFAULT_IMG')->value('value');
                    $user_id = $model->insertGetId($save_data);
                }
                
                if ( empty($user_id) ) {
                    throw new \Exception("保存失败");
                }
                // 生成token
                $token_data = [
                    'user_id'=>$user_id,
                    'access_token'=>uuidCreate(),
                    'expiry_time'=>date('Y-m-d H:i:s',strtotime('+7 days')),
                    'session_key'=>$user_code['session_key'],
                    'openid'=>$save_data['openid']
                ];
                if ( !TokenModel::insert($token_data) ) {
                    throw new \Exception("token生成失败");
                }
                Db::commit();

                $token_data['is_first'] = 1;
                return apiResult('2000','登录成功',$token_data);
            } catch (\Exception $e) {
                // 更新失败 回滚事务
                Db::rollback();
                return apiResult('5000',$e->getMessage());
            }
        }else{
            return apiResult('5000','获取openid失败');
        }
    }

    // 绑定账号
    public function bindAccount(){
        $openid = $this->login_user['openid'];
        if (empty($openid)) {
            exception('请登录后操作',400);
        }

        $param = file_get_contents('php://input');
        $param = json_decode($param,true);

        $fields = [
            'nomust'=>['mobile','account','password']
        ];
        $save_data = paramFilter($param,$fields);
        if (empty($save_data)) {
            return apiResult('5000','无任何参数');
        }

        $model = new UserModel();
        $uinfo = $model->where('mobile',$save_data['mobile'])->find();
        if ( empty($uinfo) ) {
            return apiResult('5000','账号不存在');
        }
        if ( !empty($uinfo['openid']) && $uinfo['openid'] != $openid) {
            return apiResult('5000','账号已绑定微信，请联系管理员解除再绑定');
        }
        $roles = explode(',',$uinfo['role']);
        if ( !in_array('ck',$roles) && !in_array('admin',$roles) ) {
            return apiResult('5000','账号角色不符合');
        }

        // 账号绑定OPENID
        $model->where('mobile',$save_data['mobile'])->update([
            'openid'=>$openid
        ]);
        TokenModel::where('openid',$openid)->update(['user_id'=>$uinfo['id']]);

        return apiResult('2000','绑定成功');
    }

    // 账号密码登录
    public function alogin(){
        $param = file_get_contents('php://input');
        $param = json_decode($param,true);

        $fields = [
            'nomust'=>['account','password']
        ];
        $params = paramFilter($param,$fields);
        if (!empty($params['error_msg'])) {
            exception($params['error_msg'],400);
        }

        $model = new UserModel();
        $uinfo = $model->where('account',$params['account'])->find();
        if ( empty($uinfo) ) {
            return apiResult('5000','账号不存在');
        }
        $roles = explode(',',$uinfo['role']);
        if ( !in_array('ck',$roles) && !in_array('admin',$roles) ) {
            return apiResult('5000','账号角色不符合');
        }
        if ( $uinfo['password'] != md5($params['password']) ) {
            return apiResult('5000','密码错误');
        }

        Db::startTrans();
        try{
            // 生成token
            $token_data = [
                'user_id'=>$uinfo['id'],
                'access_token'=>uuidCreate(),
                'expiry_time'=>date('Y-m-d H:i:s',strtotime('+7 days')),
            ];
            if ( !TokenModel::insert($token_data) ) {
                throw new \Exception("token生成失败");
            }
            Db::commit();
            return apiResult('2000','登录成功',$token_data);
        } catch (\Exception $e) {
            // 更新失败 回滚事务
            Db::rollback();
            return apiResult('5000',$e->getMessage());
        }
    }

    /**
     * 更新手机号码
     * @Author   cch
     * @DateTime 2020-06-15T11:20:42+0800
     * @param    [type]                   $id           [description]
     * @param    [type]                   $encrypted_data [description]
     * @param    [type]                   $iv             [description]
     * @return   [type]                                   [description]
     */
    public function updateWxUserInfo(){
        $user_id = $this->login_user['user_id'];
        if (empty($user_id)) {
            exception('请登录后操作',400);
        }

        $param = file_get_contents('php://input');
        $param = json_decode($param,true);

        $fields = [
            'must'=>['iv','encrypted_data'],
            'nomust'=>['code']
        ];
        $params = paramFilter($param,$fields);
        if (!empty($params['error_msg'])) {
            exception($params['error_msg'],400);
        }

        $model = new UserModel();
        $config = config('config.wxparam');
        if (!empty($params['code'])) {
            $url = 'https://api.weixin.qq.com/sns/jscode2session?appid='.$config['appid'].'&secret='.$config['secret'].'&js_code='.$params['code'].'&grant_type=authorization_code';
            $user_code = file_get_contents($url); //获取session_key 跟openid 
            $user_code = json_decode($user_code,true);
            if (!empty($user_code['openid'])) {
                $token_data = [
                    'expiry_time'=>date('Y-m-d H:i:s',strtotime('+7 days')),
                    'session_key'=>$user_code['session_key'],
                    'is_first'=>0
                ];
                if ( !TokenModel::where('user_id',$user_id)->update($token_data) ) {
                    return apiResult('5000','更新session_key异常');
                }
            }
        }

        $session_key = TokenModel::where('user_id',$user_id)->order('expiry_time','desc')->value('session_key');
        $result = xcxDecryptData($session_key,$params['encrypted_data'],$params['iv']);
        if ($result['status'] == 0) {
            return apiResult('2000',$result['msg']);
        }
        if (!empty($result['data'])) {
            $data = $model->where('id',$user_id)->find();
            
            $save_data = [
                'nickname'=>$result['data']['nickName'],
                'headimgurl'=>$result['data']['avatarUrl']
            ];
            if ( $model->where('id',$user_id)->update($save_data) !== false ) {
                return apiResult('2000','授权成功');
            }else{
                return apiResult('5000','更新失败，请重试');
            }
        }else{
            return apiResult('5000','获取数据失败');
        }
    }

    public function updateWxMobile(){
        $openid = $this->login_user['openid'];
        if (empty($openid)) {
            exception('请登录后操作',400);
        }

        $param = file_get_contents('php://input');
        $param = json_decode($param,true);
        // dump($param);die;

        // $param = '{"code":"0a37TFFa1KeWAG0lQMGa16L2qg17TFFx","iv":"0OS8+4oVjUM98UE0eI6kNg==","encrypted_data":"mtl/9bo3Zxyp0SIdW+kJgWIf9oYVm9yMZ+aeWyIyujCYblqzZ7mnLx6pOhm5PbCoelpu4ntzJk9nnxtmRuT5wjUNDx+tAm/I/7r8WOU5n67xe3Q8IjWhaxbt4RPXfAeGBTm6y57/0obujnMsCqRqbP4av2gVrhhuz0gwShIguFMfuXYwjphrj+X1S18JgUSRFii/LRVc2ipZcKHCYTkgAg=="}';
        // $param = json_decode($param,true);


        $fields = [
            'must'=>['iv','encrypted_data'],
            'nomust'=>['code']
        ];
        $params = paramFilter($param,$fields);
        if (!empty($params['error_msg'])) {
            exception($params['error_msg'],400);
        }
        $model = new UserModel();
        $config = config('config.wxparam');
        if (!empty($params['code'])) {
            $url = 'https://api.weixin.qq.com/sns/jscode2session?appid='.$config['appid'].'&secret='.$config['secret'].'&js_code='.$params['code'].'&grant_type=authorization_code';
            $user_code = file_get_contents($url); //获取session_key 跟openid
            $user_code = json_decode($user_code,true);
            if (!empty($user_code['openid'])) {
                $token_data = [
                    'expiry_time'=>date('Y-m-d H:i:s',strtotime('+7 days')),
                    'session_key'=>$user_code['session_key'],
                    'is_first'=>0
                ];
                if ( !TokenModel::where('openid',$openid)->update($token_data) ) {
                    return apiResult('5000','更新session_key异常');
                }
            }
        }

        $session_key = TokenModel::where('openid',$openid)->order('expiry_time','desc')->value('session_key');
        $result = xcxDecryptData($session_key,$params['encrypted_data'],$params['iv']);
        if ($result['status'] == 0) {
            return apiResult('5000',$result['msg']);
        }
        $mobile = $result['data']['phoneNumber'];
        return apiResult('2000','授权成功',$mobile);
    }

    /**
     * 保存
     * @Author   cch
     * @DateTime 2020-05-26T17:22:32+0800
     * @return   [type]                   [description]
     */
    public function update(){
        $user_id = $this->login_user['user_id'];
        if (empty($user_id)) {
            exception('请登录后操作',400);
        }

        $param = file_get_contents('php://input');
        $param = json_decode($param,true);

        $fields = [
            'nomust'=>['truename','headimgurl','mobile','nickname','remark','birthday','email','company','signature']
        ];
        $save_data = paramFilter($param,$fields);
        if (empty($save_data)) {
            return apiResult('5000','无任何更改');
        }

        $model = new UserModel();
        $data = $model->where('id',$user_id)->find();

        if ( $model->where('id',$user_id)->update($save_data) !== false ) {
            return apiResult('2000','更新成功');
        }else{
            return apiResult('2000','提交成功',$id);
        }
    }

    public function statistics(){
        $user_id = $this->login_user['user_id'];
        if (empty($user_id)) {
            exception('请登录后操作',400);
        }
        $start_time = input('start_time',date('Y-m-d'));
        $start_time = strtotime($start_time.' 00:00:00');
        $end_time = input('end_time',date('Y-m-d'));
        $end_time = strtotime($end_time.' 23:59:59');

        $data = [];
        // 累计查勘量
        $data['total_num'] = Db::name('oform')->where([
            ['ck_aid','=',$user_id],
            ['ck_time','between',[$start_time,$end_time]]
        ])->count();
        // 今日查勘量
        $data['attach_num'] = Db::name('order_attach')->where([
            ['user_id','=',$user_id],
            ['ctime','between',[$start_time,$end_time]]
        ])->count();
        

        return apiResult('2000','获取成功',$data);
    }

    public function statistics2(){
        $user_id = $this->login_user['user_id'];
        if (empty($user_id)) {
            exception('请登录后操作',400);
        }
        $data = [];
        $curdate = strtotime(date('Y-m-d'));
        $curmoth = strtotime(date('Y-m-01'));
        // 今日查勘量
        $data['td_num'] = Db::name('oform')->where([
            ['ck_aid','=',$user_id],
            ['ck_time','>=',$curdate]
        ])->count();
        // 昨日查勘量
        $data['yd_num'] = Db::name('oform')->where([
            ['ck_aid','=',$user_id],
            ['ck_time','between',[strtotime('-1 days',$curdate),$curdate]]
        ])->count();
        // 本月查勘量
        $data['month_num'] = Db::name('oform')->where([
            ['ck_aid','=',$user_id],
            ['ck_time','>=',$curmoth]
        ])->count();
        // 累计查勘量
        $data['total_num'] = Db::name('oform')->where([
            ['ck_aid','=',$user_id],
        ])->count();

        return apiResult('2000','获取成功',$data);
    }



}
